function roundFractional(x,n){
      return Math.round(x*Math.pow(10,n))/Math.pow(10,n);
}
$(()=>{
  //get dom elem得到对象元素
    let $width = $("#width"),
        $height =  $("#height"),
        $btnCal = $("#calc"),
        $form = $('#main'),
        $perimeter = $("#perimeter"),
        $widthValidate = $("#width-validate"),
        $heightValidate = $("#height-validate"),
        $area = $("#area");

  $forkMeGH.show("https://www.baidu.com")

//字符级校验
  $width.keypress((e)=>{
    let key = e.key,
        val = e.target.value,
        pos = e.target.selectionStart;
    val = val.slice(0,pos)+key+val.slice(pos,val.length);
    console.log(val);
   /* if(/[abcdf-zABCDF-Z`~!@#$%^&*()=_+[\]{}|;:'",<>/?\\]/.test(key) e.preventDefault());
  */
    if(!/^(0|[1-9]\d*)(\.\d+)?((e|E)(\+|-)?\d+)?$/.test(val) )e.preventDefault();
  });

  $height.keypress((e)=>{  
    let key = e.key,
        val = e.target.value,
        pos = e.target.selectionStart;
    val = val.slice(0,pos)+key+val.slice(pos,val.length);
    if(!/^(0|[1-9]\d*)(\.\d+)?((e|E)(\+|-)?\d+)?$/.test(val)) e.preventDefault();
  });

//字段级校验 (光标，焦点，迁移的时候)

 /* //多字段时使用冒泡机制
  $form.focusout((e)=>{
    console.log(e.target);
  })*/
  $width.focusout(()=>{
    if(!validate($width,$widthValidate)){
      //如果不符合规定光标聚焦错误位置
      $width.select();
    }
  });

  $height.focusout(()=>{
    if(!validate($height,$heightValidate)){
      $height.select();
    }
  });


//表单级校验
  //calc button click
    $btnCal.click(()=>{
  //get value得到用户输入数据
      let w = Number($width.val()),
          h = Number($height.val());
  //validate校验
      if(validate($width,$widthValidate) && validate($height,$heightValidate)){
  //calc计算
        let p = (w + h) * 2,
          a = w * h;
  //output输出赋值
        $perimeter.val(roundFractional(p,2));
        $area.val(roundFractional(a,2));
      }
    });
});

function validate(input,output){
  console.log(input.val());
  //is empty是否为空？
  if(input.val()=== ''){
    output.html('该字段不能为空');
    return false;
  }else{
    output.html('');
  }

  //is number是否为数值？
  let val = Number(input.val());
  if(isNaN(val)){
    output.html('该字段应该是数值');
    return false;
  }else{
    output.html('');
  }

  //is + 是否大于0？
  if(val<=0){
    output.html('该字段不能小于等于零');
    return false;
  }else{
    output.html('')
  }

  return true;

}
